#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <readconf.h>

#define CMP_STR		'='
#define PORT_MIN	1024
#define PORT_MAX	65535

static int get_conf_line(char *buf, size_t num);

int read_conf(void)
{
	FILE *fp;
	char *path;
	int ret;
	char *linebuf;
	size_t linenum;

	path = CONF_PATH""CONF_CMT_FILE;
	fp = fopen(path, "r");
	if (fp == NULL) {
		perror("fopen()");
		return -1;
	}

	linebuf = NULL;
	linenum = 0;
	while (1) {
		ret = getline(&linebuf, &linenum, fp);
		if (ret == -1) {
			if (feof(fp) == 0) {	//fp isn't End of File, so it's error.
				return -1;
			}
			break;			//End of File
		}

		ret = get_conf_line(linebuf, linenum);
		if (ret == -1) {
			continue;
		}
	}

	free(linebuf);
	return 0;
}

static int get_conf_line(char *buf, size_t num)
{
	int no, port_num;
	char *ch;

	if (num == 1) {				//blank line
		return 0;
	}
	if (buf[0] == REMARK_STR) {		//注释行
		return 0;
	}

	ch = strchr(buf, CMP_STR);
	if (ch == NULL) {
		return -1;
	}
	no = ch - &buf[0];			//获取变量名长度
	port_num = atoi(ch + 1);
	if (port_num <= PORT_MIN || port_num >= PORT_MAX) {
		return -1;
	}

	if (strncmp(buf, STR_OPT, no) == 0) {
		OPT_PORT = port_num;
	} else if (strncmp(buf, STR_CMT, no) == 0) {
		CMT_PORT = port_num;
	} else if (strncmp(buf, STR_STATUS, no) == 0) {
		STATUS_PORT = port_num;
	} else if (strncmp(buf, STR_CONN, no) == 0) {
		CONN_PORT = port_num;
	}

	return 0;
}

int get_opt_port(void)
{
	return OPT_PORT;
}

int get_cmt_port(void)
{
	return CMT_PORT;
}

int get_status_port(void)
{
	return STATUS_PORT;
}

int get_conn_port(void)
{
	return CONN_PORT;
}

